package com.example.demo.sensitive.controller;

import com.example.demo.sensitive.service.impl.CheckTaskServiceImpl;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName SystemManagementController
 * @Description 系统管理控制器 - 提供系统监控和维护功能
 * @Author System
 * @Date 2025/9/25
 **/
@RestController
@RequestMapping("/api/system")
public class SystemManagementController {

    private static final Log log = LogFactory.get();
    
    @Autowired
    private CheckTaskServiceImpl checkTaskService;

    /**
     * 获取系统健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<CheckTaskServiceImpl.SystemHealth> getSystemHealth() {
        try {
            CheckTaskServiceImpl.SystemHealth health = checkTaskService.getSystemHealth();
            log.debug("获取系统健康状态: {}", health.getStatus());
            return ResponseEntity.ok(health);
        } catch (Exception e) {
            log.error("获取系统健康状态失败: {}", e.getMessage(), e);
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 手动触发超时任务处理
     */
    @PostMapping("/cleanup/timeout")
    public ResponseEntity<String> handleTimeoutTasks(@RequestParam(defaultValue = "30") int timeoutMinutes) {
        try {
            log.info("手动触发超时任务处理，超时阈值: {} 分钟", timeoutMinutes);
            checkTaskService.handleTimeoutTasks(timeoutMinutes);
            return ResponseEntity.ok("超时任务处理完成");
        } catch (Exception e) {
            log.error("手动处理超时任务失败: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body("处理失败: " + e.getMessage());
        }
    }

    /**
     * 手动触发旧任务清理
     */
    @PostMapping("/cleanup/old")
    public ResponseEntity<String> cleanupOldTasks(@RequestParam(defaultValue = "7") int days) {
        try {
            log.info("手动触发旧任务清理，清理天数: {} 天", days);
            checkTaskService.manualCleanup(days);
            return ResponseEntity.ok("旧任务清理完成");
        } catch (Exception e) {
            log.error("手动清理旧任务失败: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body("清理失败: " + e.getMessage());
        }
    }

    /**
     * 手动触发定时清理（仅用于测试）
     */
    @PostMapping("/cleanup/scheduled")
    public ResponseEntity<String> triggerScheduledCleanup() {
        try {
            log.info("手动触发定时清理任务（测试用）");
            checkTaskService.cleanupOldTasks();
            return ResponseEntity.ok("定时清理任务已执行");
        } catch (Exception e) {
            log.error("手动执行定时清理失败: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body("执行失败: " + e.getMessage());
        }
    }
}
